#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -z "$LMD_APPS_DIR" ]; then
   echo "Error: Env LMD_APPS_DIR is not defined."
   exit 1
else 
   echo "Env LMD_APPS_DIR: "$LMD_APPS_DIR
fi

export CURRENT_APP_PATH="${LMD_APPS_DIR}/lmstudio"
mkdir -p "$CURRENT_APP_PATH"
if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/lmstudio/env_read.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/download_utils.sh"
echo "lmdprogress:5"

function install_for_mac {
   INSTALLER_URL=$_MAC_DOWNLOAD_URL
   INSTALLER_FILE_PATH="$CURRENT_APP_PATH/${_MAC_INSTALLER_FILE_NAME}"
   echo "start download: "$INSTALLER_URL
   
   echo "lmdprogress:50"
   download_with_resume "$INSTALLER_FILE_PATH" $INSTALLER_URL
   echo "downloaded."

   echo "lmdprogress:70"
   echo "LM Studio has been downloaded. You should install it by yourself. The final step is very easy."
   
   
   MOUNT_APP_PATH="/Volumes/lmstudio"
   # mount .dmg file
   hdiutil attach "$INSTALLER_FILE_PATH" -mountpoint $MOUNT_APP_PATH

   echo "lmdprogress:90"
   if [ $? -eq 0 ]; then
      echo "DMG file has been mounted successfully."
   else
      echo "Failed to mount DMG file."
   fi

   open $MOUNT_APP_PATH

   # TARGET_APP_FILE="$CURRENT_APP_PATH/LM Studio.app"
   # if [ -d "$TARGET_APP_FILE" ]; then
   #    echo "App file exist, delete: "$TARGET_APP_FILE
   #    rm -rf $TARGET_APP_FILE
   # fi

   # echo "start copy."
   # cp -R "$MOUNT_APP_PATH/LM Studio.app" $CURRENT_APP_PATH
   # echo "copy ok."
   # hdiutil detach $MOUNT_APP_PATH
   
   # echo "detach ok."
}

function install_for_win {
   cpu_arch=$(powershell -NoProfile -Command "([System.Environment]::GetEnvironmentVariable('PROCESSOR_ARCHITECTURE'))")
   if [[ "$cpu_arch" == "ARM64" ]]; then
      echo "ARM CPU"
      INSTALLER_URL=$_WINDOWS_ARM64_DOWNLOAD_URL
      INSTALLER_FILE_PATH="$CURRENT_APP_PATH/${_WINDOWS_ARM64_INSTALLER_FILE_NAME}"
   elif [[ "$cpu_arch" == "AMD64" ]]; then
      echo "x64 CPU"
      INSTALLER_URL=$_WINDOWS_X64_DOWNLOAD_URL
      INSTALLER_FILE_PATH="$CURRENT_APP_PATH/${_WINDOWS_X64_INSTALLER_FILE_NAME}"
   else
      echo "do not support: $cpu_arch"
      exit 1
   fi
   echo "lmdprogress:40"
   echo "start download: "$INSTALLER_URL
   download_with_resume "$INSTALLER_FILE_PATH" $INSTALLER_URL
   echo "downloaded."
   echo "lmdprogress:80"
   "$INSTALLER_FILE_PATH"
}

if [ -f /etc/os-release ]; then
   echo "Linux system."
   echo "Not supported."
   exit 1
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   install_for_mac
elif current_os_is_windows; then
   echo "Windows system."
   install_for_win
else
   echo "Unknown OS"
fi

echo "lmdprogress:100"
